<template>
  <div class="userHomePage">
    <a-card title="个人主页" :bordered="false">
      <a-form :model="form" layout="vertical" @finish="onSubmit">
        <a-form-item label="用户名" name="userName">
          <a-input v-model:value="form.userName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="简介" name="userProfile">
          <a-input v-model:value="form.userProfile" placeholder="请输入个人简介" />
        </a-form-item>
        <a-form-item label="头像链接" name="userAvatar">
          <a-input v-model:value="form.userAvatar" placeholder="请输入头像 URL" />
        </a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit">保存</a-button>
          <a-button @click="reset">重置</a-button>
        </a-space>
      </a-form>
    </a-card>
  </div>
  
</template>

<script lang="ts" setup>
import { onMounted, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/loginUser.ts'
import { getLoginUser, updateUser } from '@/api/userController.ts'

const loginUserStore = useLoginUserStore()

const form = reactive<{ id?: number; userName?: string; userProfile?: string; userAvatar?: string }>(
  {
    id: undefined,
    userName: '',
    userProfile: '',
    userAvatar: '',
  }
)

const load = async () => {
  // 优先使用 store 的登录用户，若无则从后端拉取
  if (!loginUserStore.loginUser?.id) {
    const res = await getLoginUser()
    if (res.data.code === 0 && res.data.data) {
      loginUserStore.setLoginUser(res.data.data)
    }
  }
  const u = loginUserStore.loginUser
  if (u?.id) {
    form.id = u.id
    form.userName = u.userName
    form.userProfile = u.userProfile
    form.userAvatar = u.userAvatar
  }
}

onMounted(() => {
  load()
})

const onSubmit = async () => {
  if (!form.id) {
    message.error('未登录或用户信息缺失')
    return
  }
  const res = await updateUser({
    id: form.id,
    userName: form.userName,
    userProfile: form.userProfile,
    userAvatar: form.userAvatar,
  })
  if (res.data.code === 0) {
    message.success('保存成功')
    // 同步更新到 store
    loginUserStore.setLoginUser({
      ...loginUserStore.loginUser,
      userName: form.userName,
      userProfile: form.userProfile,
      userAvatar: form.userAvatar,
    })
  } else {
    message.error('保存失败，' + res.data.message)
  }
}

const reset = () => {
  load()
}
</script>

<style scoped>
.userHomePage {
  max-width: 720px;
  margin: 24px auto;
}
</style>


